package com.rds.common.core.service;

import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.domain.entity.DynamicVo;
import com.rds.common.core.mapper.DynamicMapper;
import com.rds.common.utils.DateUtils;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.StringUtils;
import com.rds.common.utils.rds.HistoryRecordUtil;
import com.rds.common.utils.uuid.SnowFlakeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;

/**
 * 文档管理--Service实现类
 * @author rds
 * @updater libin
 * @updateDate : 2024-2-19
 */
@Service
public class DocumentService
{
    @Autowired
    private DynamicMapper dynamicMapper;
    /***
     * 查询文档
     * @param queryWrapper 查询条件
     * @return 文档对象
     */
    public List<HashMap<String,Object>> selectDocList(ArrayList<String> queryWrapper) {
        DynamicVo docDynamicVo=new DynamicVo();
        docDynamicVo.setTableName("rda_document");
        docDynamicVo.setQueryWrapper(queryWrapper);
        docDynamicVo.setOrderBy(" create_time desc");
        List<HashMap<String,Object>> list=dynamicMapper.selectList(docDynamicVo);
        //循环查找文件
        for(HashMap<String,Object> doc:list){
            List<HashMap<String,Object>> fileList=selectFileListByDocId((Long) doc.get("id"));
            doc.put("fileList",fileList);
        }
        return list;
    }

    /***
     * 根据文档id 查询生效状态的文件附件对象
     * @param docId 文档id
     * @return 文件附件对象
     */
    public List<HashMap<String,Object>> selectFileListByDocId(Long docId) {
        DynamicVo fileDynamicVo=new DynamicVo();
        fileDynamicVo.setTableName("rda_file");
        ArrayList<String> fileQueryWrapper=new ArrayList<>();
        fileQueryWrapper.add("and doc_id="+docId);
        fileQueryWrapper.add("and status=1");
        fileDynamicVo.setQueryWrapper(fileQueryWrapper);
        fileDynamicVo.setOrderBy(" revision desc");
        return dynamicMapper.selectList(fileDynamicVo);
    }

    /***
     * 根据文档id 查询文件夹关系
     * @param docId 文档id
     * @return 文件附件对象
     */
    public List<HashMap<String,Object>> selectFolderRelListByDocId(Long docId) {
        DynamicVo dynamicVo=new DynamicVo();
        dynamicVo.setTableName("rda_folder_rel");
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and docid="+docId);
        dynamicVo.setQueryWrapper(queryWrapper);
        return dynamicMapper.selectList(dynamicVo);
    }

    /***
     * 根据文件夹id 查询文档对象
     * @param folderId 文件夹id
     * @return 文件附件对象
     */
    public List<HashMap<String,Object>> selectFolderDoc(Long folderId) {
        DynamicVo dynamicVo=new DynamicVo();
        dynamicVo.setTableName("rda_folder_rel");
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and folderid="+folderId);
        dynamicVo.setQueryWrapper(queryWrapper);
        List<HashMap<String,Object>> relList=dynamicMapper.selectList(dynamicVo);
        if(relList.size()>0){
            List<HashMap<String,Object>> list=dynamicMapper.selectListByIds("rda_document", parseList2LongArray(relList,"folderid"));
            //循环查找文件
            for(HashMap<String,Object> doc:list){
                List<HashMap<String,Object>> fileList=selectFileListByDocId((Long) doc.get("id"));
                doc.put("fileList",fileList);
            }
            return list;
        }
        return new ArrayList<>();
    }

    /***
     * 查询是否存在同类型，同名称，同版本的文档
     * @param typeid 类型id
     * @param name 名称
     * @param revision 版本
     * @return 文件附件对象
     */
    public List<HashMap<String,Object>> checkUniqueDocument(Integer typeid,String name,String revision) {
        DynamicVo dynamicVo=new DynamicVo();
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and typeid="+typeid);
        queryWrapper.add("and name='"+name+"'");
        queryWrapper.add("and revision='"+revision+"'");
        dynamicVo.setQueryWrapper(queryWrapper);
        dynamicVo.setTableName("rda_document");
        return dynamicMapper.selectList(dynamicVo);
    }

    /***
     * 创建文档与文件夹的关系
     * @param docId 文档id
     * @param folderId 文件夹id
     * @param folderId 文件夹id
     * @return 文件附件对象
     */
    public int insertRelDocAndFolder(Long docId,Long folderId,Long objectId) {
        Map<String, Object> folderMap=new HashMap<>();
        folderMap.put("id", SnowFlakeUtils.nextId());
        folderMap.put("docid",docId);
        folderMap.put("folderid",folderId);
        folderMap.put("projectid", objectId);
        folderMap.put("create_time", DateUtils.getNowDate());
        return dynamicMapper.insertData("rda_folder_rel",folderMap);
    }

    /***
     * 批量插入文件
     * @param fileList 文件数据
     * @param docId 文档id
     * @return 文件名称
     */
    public StringBuilder insertBatchFile(List<?> fileList,Long docId) {
        StringBuilder fileNameSting= new StringBuilder();
        String username = SecurityUtils.getUsername();
        List<Map<String, Object>> fileBatchList=new ArrayList<>();
        for (Object fileInfo : fileList) {
            if (fileInfo instanceof Map) { // 假设fileInfo是一个Map<String, Object>类型的对象
                Map<String, Object> fileMap=(Map<String, Object>) fileInfo;
                String fileName = fileMap.get("fileName").toString();
                long fid=SnowFlakeUtils.nextId();
                Map<String, Object> map=new HashMap<>();
                map.put("id",fid);
                map.put("doc_id",docId);
                map.put("name",fileName);
                map.put("path",fileMap.get("path").toString());
                map.put("file_size",""+Integer.parseInt(fileMap.get("fileSize").toString())/1024);
                map.put("username",username);
                map.put("file_id",fid);
                map.put("create_time",DateUtils.getNowDate());
                fileNameSting.append(fileName).append(";");
                fileBatchList.add(map);
            }
        }
        dynamicMapper.insertBatchData("rda_file",fileBatchList);
        return fileNameSting;
    }

    /***
     * 修改文档
     * @param data 文档信息
     * @return 文件附件对象
     */
    public int updateDocument(Map<String, Object> data) {
        /*直接更新当前文档对象**/
        Long dId= (Long) data.get("id");
        data.put("modify_time",DateUtils.getNowDate());
        ArrayList<String> updateWrapper=new ArrayList<>();
        updateWrapper.add("id="+dId);
        data.remove("companyName");
        data.remove("folderName");
        data.remove("classfication");
        data.remove("create_time");
        data.remove("publish_time");
        if(data.get("recordid")==null || data.get("recordid").equals("")){
            data.remove("recordid");
        }
        return dynamicMapper.updateData("rda_document",data,updateWrapper);
    }

    /***
     * 添加已存在文档
     * @param ids 文档id
     * @param parentId 文件夹id
     * @param objectId 文件夹id
     * @return 文件附件对象
     */
    public int addExisting(String[] ids,Long parentId,Long objectId) {
        List<Map<String, Object>> batchList=new ArrayList<>();
        for(String id:ids){
            Map<String, Object> map=new HashMap<>();
            map.put("id",SnowFlakeUtils.nextId());
            map.put("parentid",parentId);
            map.put("projectid",objectId);
            map.put("docid",Long.valueOf(id));
            map.put("create_time",DateUtils.getNowDate());
            batchList.add(map);
        }
        return dynamicMapper.insertBatchData("rda_folder",batchList);
    }

    /***
     * 根据公司id查询公司信息
     * @param companyId 公司id
     * @return 文件附件对象
     */
    public HashMap<String,Object> selectCompanyByCompanyId(Long companyId) {
        DynamicVo dynamicVo=new DynamicVo();
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and company_id="+ companyId);
        dynamicVo.setQueryWrapper(queryWrapper);
        dynamicVo.setTableName("sys_company");
        return dynamicMapper.selectDataByDynamic(dynamicVo);
    }

    /***
     * 根据策略id查询策略下的所有状态
     * @param policyId 策略id
     * @return 文件附件对象
     */
    public List<HashMap<String,Object>> selectStateByPolicyId(Integer policyId) {
        DynamicVo dynamicVo=new DynamicVo();
        dynamicVo.setTableName("rda_state");
        ArrayList<String> queryWrapper=new ArrayList<>();
        queryWrapper.add("and policyid="+policyId);
        dynamicVo.setQueryWrapper(queryWrapper);
        return dynamicMapper.selectList(dynamicVo);
    }

    /**
     * 将查询到的附件集合抽取只需要附件Id数组
     * 此方法只对删除全部版本适用
     * @param revisionList 文件附件集合
     * @return 附件fileId数组
     */
    public Long[] parseList2LongArray(List<HashMap<String,Object>> revisionList,String key){
        Long[] fileIds = new Long[revisionList.size()];
        for(int index = 0; index < revisionList.size();index++){
            fileIds[index] = (Long) revisionList.get(index).get(key);
        }
        return fileIds;
    }

    /**
     * 文件大小转换
     * @param size 原文件大小
     * @return 转换后的文件大小
     */
    public String readableFileSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B","KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    /***
     * 查询列表数据
     * @param queryWrapper 查询条件
     * @return 文档对象
     */
    public List<HashMap<String,Object>> selectDataList(String tableName,ArrayList<String> queryWrapper) {
        DynamicVo docDynamicVo=new DynamicVo();
        docDynamicVo.setTableName(tableName);
        docDynamicVo.setQueryWrapper(queryWrapper);
        docDynamicVo.setOrderBy(" create_time desc");
        return dynamicMapper.selectList(docDynamicVo);
    }
}
